package com.csi.utils;


import java.io.IOException;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.Properties;

/**
 * JDBC资源管理工具类
 */
public class JDBCUtils {
    private Properties properties ;

    {
        //构建对象
        properties = new Properties() ;

        try {
            //通过类加载器，找到classes目录，继而找到db.properties文件
            properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建连接
     * java.sql.Connection
     */
    protected Connection getConnection() throws SQLException {
        try {
            Class.forName(getValue("classname")) ;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        //2. 建立连接  http://www.sohu.com
        Connection connection = DriverManager.getConnection(getValue("url"),getValue("username"),getValue("password")) ;

        return connection ;
    }



    /**
     * 释放连接
     */
    protected void release(Connection connection) {
        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    protected void release(Statement statement) {
        if(statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    protected void release(ResultSet rs) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 增删改实现关闭
     * @param ps
     * @param connection
     */
    protected void release(PreparedStatement ps,Connection connection) {
        release(ps);
        release(connection);
    }

    /**
     * 查询关闭
     * @param rs
     * @param ps
     * @param connection
     */
    protected void release(ResultSet rs, PreparedStatement ps, Connection connection) {
        release(rs);
        release(ps,connection);
    }

    /**
     * 从属性文件中，获取到key对应的value值
     * @param key
     * @return
     */
    public String getValue(String key) {
        return properties.getProperty(key) ;
    }

}
